/**
 * @author: jichanghong
 * @date: 2018年8月24日下午5:36:28
 * @description:
 * @modify:
 */
package com.topscomm.mpm.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.exception.BusinessException;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.cbo.pojo.CboJobEntity;
import com.topscomm.cbo.pojo.CboUserEntity;
import com.topscomm.mpm.CustomAnnotation.BusinessValadator;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;

import java.io.*;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author: jichanghong
 * @date: 2018年8月24日下午5:36:28
 * @description:
 * @modify:
 */
public class MisStringUtil {

    /**
     * 拼接项目查询条件
     */
    public static String createWhereByUsercodeFromProject(CboUserEntity userEntity, String projectIdColumnName, String tableName) {
        StringBufferProxy sql = new StringBufferProxy();
        if (userEntity == null || StringUtil.isEmpty(userEntity.getCode())) {
            return "";
        }
//		sql.appendSingle(" exists (select pmproject.id from pmproject where {0}.{1} = pmproject.id and (pmproject.projectmanagercode = '{2}' " +
//				"or pmproject.areamanagercode = '{2}' or exists(" +
//				"select pmteam.id from pmteam where {0}.{1} = pmteam.projectid and pmteam.usercode = '{2}' and pmteam.enabled = 1)))", tableName, projectIdColumnName, userEntity.getCode());
//		String deptcodes_header = ConvertUtil.convertToString(userEntity.getValue("deptcodes_header"));

		//
		String[] params = {"misdeptheader.deptcode","'%'"};
        sql.appendSingle("exists (select pmproject.id from pmproject " +
				"LEFT JOIN misdeptheader on pmproject.ownerdeptcode like " +SQLAdapter.concat(params)
						+" where {0}.{1} = pmproject.id and (pmproject.projectmanagercode = '{2}' or  misdeptheader.usercode='{2}') )",
                tableName, projectIdColumnName, userEntity.getCode());
        //

//        String deptheadersql = "exist select misdeptheader.id from misdeptheader where misdeptheader.enabled = 1 and misdeptheader.deptcode like "+SQLAdapter.concat(params)+" and misdeptheader.usercode='" + userEntity.getCode() + "'";
//        sql.appendSingle(" or exists (select pmproject.id from pmproject where {0}.{1} = pmproject.id and {2})",
//                tableName, projectIdColumnName, deptheadersql);
        return sql.toString();
    }

    /**
     * 拼接部门查询条件（不包含上下级部门）
     * @param colname（列名）
     * @param deptautocode （多个部门编号，使用,;，；隔开）
     * @return
     */
    public static String createWhereByHisDeptautocode(String colname, String deptautocode) {
        StringBufferProxy sql = new StringBufferProxy();

        if (StringUtil.isEmpty(colname) || StringUtil.isEmpty(deptautocode))
            return "";
        String[] autocodeArray = deptautocode.split("[,;，；]");
        if (autocodeArray == null || autocodeArray.length == 0)
            return "";
        for (String autocode : autocodeArray) {
            sql.appendSingle("or {0} like '{1}%' ", colname, autocode);
        }
        String whereSql = "(" + sql.toString().substring(2) + ")";
        return whereSql;
    }

    /**
     * 将字符串写入指定文件(当指定的父路径中文件夹不存在时，会最大限度去创建，以保证保存成功！)
     * @param res            原字符串
     * @param filePath 文件路径
     * @return 成功标记
     */
    public static boolean string2File(String res, String filePath) {
        boolean flag = true;
        BufferedReader bufferedReader = null;
        BufferedWriter bufferedWriter = null;
        try {
            File distFile = new File(filePath);
            if (!distFile.getParentFile().exists()) distFile.getParentFile().mkdirs();
            bufferedReader = new BufferedReader(new StringReader(res));
            bufferedWriter = new BufferedWriter(new FileWriter(distFile));
            char buf[] = new char[1024];         //字符缓冲区
            int len;
            while ((len = bufferedReader.read(buf)) != -1) {
                bufferedWriter.write(buf, 0, len);
            }
            bufferedWriter.flush();
            bufferedReader.close();
            bufferedWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
            flag = false;
            return flag;
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedWriter != null) {
                try {
                    bufferedWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }

    /**
     * 文本文件转换为指定编码的字符串
     * @param file 文本文件
     * @param encoding 编码类型
     * @return 转换后的字符串
     * @throws IOException
     */
    public static String file2String(File file, String encoding) {
        InputStreamReader reader = null;
        StringWriter writer = new StringWriter();
        try {
            if (encoding == null || "".equals(encoding.trim())) {
                reader = new InputStreamReader(new FileInputStream(file), encoding);
            } else {
                reader = new InputStreamReader(new FileInputStream(file));
            }
            // 将输入流写入输出流
            char[] buffer = new char[1024];
            int n = 0;
            while (-1 != (n = reader.read(buffer))) {
                writer.write(buffer, 0, n);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (reader != null)
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        // 返回转换结果
        return writer.toString();
    }

    /**
     * 处理的最大数字达千万亿位 精确到分
     * @return
     */
    public static String digitUppercase(BigDecimal num) throws Exception {
        if (num.compareTo(new BigDecimal("0")) == 0) {
            return "";
        }
        String fraction[] = {"角", "分"};
        String digit[] = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
        /**
         *      仟        佰        拾         ' '  ' '    $4        $3        $2         $1
         万     $8        $7        $6         $5
         亿     $12       $11       $10        $9
         */
        String unit1[] = {"", "拾", "佰", "仟"};//把钱数分成段,每四个一段,实际上得到的是一个二维数组
        String unit2[] = {"元", "万", "亿", "万亿"}; //把钱数分成段,每四个一段,实际上得到的是一个二维数组
        BigDecimal bigDecimal = num;
        bigDecimal = bigDecimal.multiply(new BigDecimal(100));
//	        Double bigDecimal = new Double(name*100);     存在精度问题 eg：145296.8
        String strVal = String.valueOf(bigDecimal.toBigInteger());
        String head = strVal.substring(0, strVal.length() - 2);         //整数部分
        String end = strVal.substring(strVal.length() - 2);              //小数部分
        String endMoney = "";
        String headMoney = "";
        if ("00".equals(end)) {
            endMoney = "整";
        } else {
            if (!end.substring(0, 1).equals("0")) {
                endMoney += digit[Integer.valueOf(end.substring(0, 1))] + "角";
            } else if (end.substring(0, 1).equals("0") && !end.substring(1, 2).equals("0")) {
                endMoney += "零";
            }
            if (!end.substring(1, 2).equals("0")) {
                endMoney += digit[Integer.valueOf(end.substring(1, 2))] + "分";
            }
        }
        char[] chars = head.toCharArray();
        Map<String, Boolean> map = new HashMap<String, Boolean>();//段位置是否已出现zero
        boolean zeroKeepFlag = false;//0连续出现标志
        int vidxtemp = 0;
        for (int i = 0; i < chars.length; i++) {
            int idx = (chars.length - 1 - i) % 4;//段内位置  unit1
            int vidx = (chars.length - 1 - i) / 4;//段位置 unit2
            String s = digit[Integer.valueOf(String.valueOf(chars[i]))];
            if (!"零".equals(s)) {
                headMoney += s + unit1[idx] + unit2[vidx];
                zeroKeepFlag = false;
            } else if (i == chars.length - 1 || map.get("zero" + vidx) != null) {
                headMoney += "";
            } else {
                headMoney += s;
                zeroKeepFlag = true;
                map.put("zero" + vidx, true);//该段位已经出现0；
            }
            if (vidxtemp != vidx || i == chars.length - 1) {
                headMoney = headMoney.replaceAll(unit2[vidx], "");
                headMoney += unit2[vidx];
            }
            if (zeroKeepFlag && (chars.length - 1 - i) % 4 == 0) {
                headMoney = headMoney.replaceAll("零", "");
            }
        }
        return headMoney + endMoney;
    }

    //检查部门是否在给定的部门范围内，包括下级部门
    public static boolean deptCheckInclude(String deptautocodes, String deptautocode, String spiltstring) {
        int start_num = 0;
        boolean returnFlag = false;
        deptautocodes = spiltstring + deptautocodes + spiltstring;
        if (deptautocode.trim().indexOf("_") < 0)
            start_num = 2;
        else
            start_num = deptautocode.indexOf("_") + 3;
        for (int i = start_num; i <= deptautocode.length(); i = i + 2) {
            if (deptautocodes.indexOf(spiltstring + deptautocode.substring(0, i) + spiltstring) >= 0) {
                returnFlag = true;
                break;
            }
        }
        return returnFlag;
    }

    /**
     * 拼接部门层次编号的查询条件
     * @param colname
     * @param deptautocode
     * @return
     */
    public static String createWhereDeptCheckInclude(String colname, String deptautocode, String spiltstring) {
        StringBufferProxy sql = new StringBufferProxy();
        if (StringUtil.isEmpty(colname) || StringUtil.isEmpty(deptautocode))
            return "";
        int start_num = 0;
        if (deptautocode.trim().indexOf("_") < 0)
            start_num = 2;
        else
            start_num = deptautocode.indexOf("_") + 3;
        String[] params = {"'" + spiltstring + "'", colname, "'" + spiltstring, "'"};
        for (int i = start_num; i <= deptautocode.length(); i = i + 2) {
            sql.appendSingle("or {0} like '%{1}%' ", SQLAdapter.concat(params), spiltstring + deptautocode.substring(0, i) + spiltstring);
        }
        String whereSql = "(" + sql.toString().substring(2) + ")";
        return whereSql;
    }
    /**
     * 单据审批完成后要求修改单据内容，用于生成生成修改记录的json字符串
     * json内容为：{修改人code，修改人名字，修改字段[]，修改前字段值，修改后字段值，修改时间}
     * @param userEntity  用户信息
     * @param  entity     旧的单据信息
     * @param newKeyValue 新key和value
     * @param oldJsonStr 原有修改历史的字段值
     *
     * @return
     */
    public static <T extends BasicEntity> String generateModifyRecordJsonStr(CboUserEntity userEntity,T entity, Map<String,Object> newKeyValue){

        // 根据新的key，获取key的旧值
        Map<String,Object> oldMap = new HashMap<>();
        for (String key:newKeyValue.keySet()){
            // 剔除key为id的值
            if (key.equals("id")){
                oldMap.put(key,entity.getValue(key));
            }
        }
        // 生成一条新纪录
        JSONObject modifyRecord = new JSONObject();
        modifyRecord.put("modifyUserCode",userEntity.getCode());
        modifyRecord.put("modifyUserName",userEntity.getName());
        modifyRecord.put("oldKeyValue",oldMap);
        modifyRecord.put("newKeyValue",newKeyValue);
        modifyRecord.put("modifyon",new Date());
        JSONArray objects = JSON.parseArray(ConvertUtil.convertToString(entity.getValue("modifyrecord")));
        if (objects==null){
            objects =  new JSONArray();
        }
        objects.add(modifyRecord);
       return objects.toJSONString();
    }

    public static void main(String[] args) {
        Map<String, Object> aaa = new HashMap<>();
        aaa.put("aa",1);
        aaa.put("bb",2);
        System.out.println(aaa.keySet().toString());
        aaa.keySet().toString();
    }
}
